//
//  b.cpp
//  c
//
//  Created by z on 2020/6/14.
//  Copyright © 2020 z. All rights reserved.
//

#include "b.hpp"
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
#include <string.h>
#include <arpa/inet.h>
#include <poll.h>
#include <vector>
#include <iostream>

uint32_t ip_str2int(const char* a)
{
    struct in_addr tt;
    inet_aton(a,&tt);
    return tt.s_addr;
}

class mybuf
{
public:
    std::vector<char> data;
    int readPos=0;
    void clear()
    {
        readPos=0;
        data.clear();
    }
    void writeDWord(uint32_t a)
    {
        data.insert(data.end(),(char*)&a,(char*)&a+4);
    }
    void writeArr(char* a,int l)
    {
        data.insert(data.end(),a,a+l);
    }
    void writeDouble(double a)
    {
        data.insert(data.end(),(char*)&a,(char*)&a+8);
    }
    void writeByte(char a)
    {
        data.push_back(a);
    }
    void readArr(char*a,int l)
    {
        for(int i=0;i<l;i++)
        {
            a[i]=data[readPos];
            readPos++;
        }
    }
    uint16_t  readWord()
    {
        char b[2];
        readArr(b,2);
        uint16_t a;
        memcpy(&a, b, 2);
        return a;
    }
};
std::vector<int> ports;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void lock()
{
     pthread_mutex_lock(&mutex);
}
void unlock()
{
     pthread_mutex_unlock(&mutex);
}
int getLen()
{
    return ports.size();
}
int getIndex(int i)
{
    return ports[i];
}
void getBuf(char *a)
{
    a[0]=10;
    a[2]=200;
}
int b()
{
    mybuf w;
    w.writeArr("hfeiffcc", 8);
    uint32_t t = std::time(0);
    for(int i=0;i<4;i++)
        w.writeDWord(t);
    w.writeDWord(100);
    w.writeByte(2);
    w.writeArr("dd",2);
    w.writeDWord(500);
    w.writeDWord(200*1024);
    w.writeDWord(8080);
    w.writeDWord(100);
    w.writeDWord(1000);
    w.writeDWord(200*1024);
    w.writeDouble(0.01);
    w.writeDouble(0.02);
    int sendSock =  socket (AF_INET, SOCK_DGRAM, 0);
    struct sockaddr_in add;
    add.sin_addr.s_addr=ip_str2int("42.51.28.250");
    add.sin_port =  htons(8895);
    add.sin_family = AF_INET;
    sendto(sendSock,&w.data[0],w.data.size(),0,(struct sockaddr *) &add, sizeof(add));
    char buf[1000];
    socklen_t ll=sizeof(add);
    int l= recvfrom(sendSock, (void*)buf, 1000, 0,(struct sockaddr *) &add, &ll);
    w.clear();
    w.writeArr(buf,l);
    
    w.readArr(buf,16 );
    lock();
    ports.clear();
    for(int i=0;i<100;i++)
    {
        int t=  w.readWord();
        std::cout<<t<<",";
        ports.push_back(t);
    }
    unlock();
    std::cout<<std::endl;
    
return 0;
    
}
